import AMapLoader from '@amap/amap-jsapi-loader';
import VGE from '../../VGE';
import { Camera } from './Camera';
import { Misc } from './Misc';

export default class AMapApp {
	static async open(sceneData = {}) {
		try {
			const {
				sceneUrl,
				container,
				cameraParams = {},
				homeView = {},
				token,
				loadOptions = {}
			} = sceneData;

			await VGE.util.findOrCreateDom(container);

			if (sceneUrl) {
				this.AMap = await this.loadScript({ sceneUrl, token });
			} else {
				const options = Object.assign({ key: token }, loadOptions);
				this.AMap = await AMapLoader.load(options);
			}
			this.viewer = new this.AMap.Map(container, loadOptions);

			this.homeViewParams = homeView;

			this.camera = new Camera(this.viewer);
			this.misc = new Misc(this.viewer);

			this.camera.flyTo(cameraParams);

			return this.viewer;
		} catch (e) {
			console.error(e);
		}
	}

	static async close() {
		delete window._babelPolyfill;
		this.viewer?.destroy();
	}

	static async loadScript({ sceneUrl, token }) {
		// 加载高德地图
		if (window.AMap) return Promise.resolve(window.AMap);
		return new Promise((resolve, reject) => {
			const script = document.createElement('script');
			script.src = `${sceneUrl}&key=${token}`;
			script.onload = () => resolve(window.AMap);
			script.onerror = reject;
			document.body.appendChild(script);
		});
	}
}
AMapApp.viewer = null;
AMapApp.homeViewParams = {};
AMapApp.camera = null;
AMapApp.misc = null;
